package com.jcfk.eam.service.base;

import cn.hutool.core.util.StrUtil;
import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jcfk.common.business.service.BaseService;
import com.jcfk.common.core.utils.BeanUtils;
import com.jcfk.common.core.utils.IdUtils;
import com.jcfk.common.security.utils.SecurityUtils;
import com.jcfk.common.web.domain.DataPage;
import com.jcfk.common.web.domain.RetResult;
import com.jcfk.eam.dao.base.EamLocationInfoDao;
import com.jcfk.eam.domain.dto.base.EamLocationInfoDTO;
import com.jcfk.eam.domain.po.base.EamLocationInfo;
import com.jcfk.eam.domain.query.base.EamLocationInfoQuery;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

import static com.jcfk.common.core.utils.BeanUtils.convertList;

/**
 * 位置信息 服务
 *
 * @author awei
 * @email 522891237@gqq.com
 * @date 2024-03-25
 */
@Service
public class EamLocationInfoService extends BaseService<EamLocationInfoDao, EamLocationInfo> {

    /**
     * 获取位置列表
     *
     * @param query 查询条件
     * @return List<EamLocationInfoDTO>
     */
    public List<EamLocationInfoDTO> getList(EamLocationInfoQuery query) {
        // 查询条件
        QueryWrapper<EamLocationInfo> qw = new QueryWrapper<>();
        qw.lambda().likeRight(!StrUtil.isEmpty(query.getLocationCode()), EamLocationInfo::getLocationCode, query.getLocationCode());
        qw.lambda().likeRight(!StrUtil.isEmpty(query.getLocationName()), EamLocationInfo::getLocationName, query.getLocationName());
        qw.lambda().eq(query.getEnabled() != null, EamLocationInfo::getEnabled, query.getEnabled());
        qw.lambda().eq(EamLocationInfo::getDeleted, 0);
        // 查询数据
        List<EamLocationInfo> list = super.list(qw);

        return convertList(list, EamLocationInfoDTO.class);
    }

    /**
     * 根据条件获取位置信息树
     *
     * @param query 查询条件
     */
    public List<EamLocationInfoDTO> getTree(EamLocationInfoQuery query) {
        List<EamLocationInfoDTO> tree = new ArrayList<>();
        //获取所有门户目录
        List<EamLocationInfoDTO> allList = this.getList(query);
        //排序
        allList.sort(Comparator.comparing(EamLocationInfoDTO::getSort));

        Map<String, List<EamLocationInfoDTO>> parentChildMap = new HashMap<>();
        // 将节点按照父节点进行分组
        for (EamLocationInfoDTO node : allList) {
            String parentId = node.getParentId();
            parentChildMap.computeIfAbsent(parentId, k -> new ArrayList<>()).add(node);
        }

        // 递归组装树结构
        buildTree(tree, parentChildMap, "0");

        return tree;
    }

    private static void buildTree(List<EamLocationInfoDTO> tree, Map<String, List<EamLocationInfoDTO>> parentChildMap, String parentId) {
        List<EamLocationInfoDTO> children = parentChildMap.get(parentId);
        if (children != null) {
            for (EamLocationInfoDTO child : children) {
                List<EamLocationInfoDTO> grandchildren = parentChildMap.get(child.getId());
                if (grandchildren != null) {
                    buildTree(child.getNodes(), parentChildMap, child.getId());
                }
                tree.add(child);
            }
        }
    }


    /**
     * EamLocationInfo分页查询
     *
     * @param page  分页设置
     * @param query 查询条件
     * @return 分页查询结果
     */
    public DataPage<EamLocationInfoDTO> queryByPage(DataPage<EamLocationInfoDTO> page, EamLocationInfoQuery query) {
        // 分页查询
        query.setLocationName(StringUtils.isEmpty(query.getLocationName()) ? query.getLocationName() : query.getLocationName() + "%");
        page = this.baseMapper.queryByPage(page, query);
        return page;
    }


    /**
     * 判断EamLocationInfo是已经存在
     *
     * @param dto
     * @return
     */
    public RetResult<String> isValid(EamLocationInfoDTO dto) {
        QueryWrapper<EamLocationInfo> qw = new QueryWrapper<>();
        Integer count = 0;
        // 判断编号
        if (StrUtil.isNotEmpty(dto.getLocationCode())) {
            //修改时添加条件
            if (!StrUtil.isEmpty(dto.getId())) {
                qw.lambda().ne(EamLocationInfo::getId, dto.getId());
            }
            qw.lambda().eq(EamLocationInfo::getLocationCode, dto.getLocationCode());
            qw.lambda().eq(EamLocationInfo::getDeleted, 0);

            count = this.baseMapper.selectCount(qw);
            if (count > 0) {
                return RetResult.fail("位置编号已存在");
            }
        }
        return RetResult.ok();
    }

    /**
     * 插入位置
     *
     * @param dto 插入对象
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public void insert(EamLocationInfoDTO dto) {

        // 保存
        EamLocationInfo item = new EamLocationInfo();
        BeanUtils.copyProperties(dto, item);
        item.setId(IdUtils.simpleUUID());
        this.setDefaultValue(item);
        this.setAllInfo(item);
        super.save(item);

    }

    /**
     * 更新位置
     *
     * @param dto 更新对象
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public void update(EamLocationInfoDTO dto) {

        // 保存
        EamLocationInfo item = new EamLocationInfo();
        BeanUtils.copyProperties(dto, item);

        // 默认数据
        this.setDefaultValue(item);
        this.setAllInfo(item);
        super.updateById(item);
    }

    /**
     * 根据批量主键删除位置(逻辑删除)
     *
     * @param dto
     * @return bool
     */
    @Transactional(rollbackFor = Exception.class)
    public Boolean logicDeleteList(EamLocationInfoDTO dto) {

        EamLocationInfo item = new EamLocationInfo();

        this.setDefaultValue(item);
        item.setVersion(dto.getVersion());
        item.setDeleted(1);

        QueryWrapper<EamLocationInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("id", dto.getIds());

        return this.update(item, queryWrapper);
    }

    /**
     * 设置添加默认值
     *
     * @param item 添加对象
     */
    public void setDefaultValue(EamLocationInfo item) {
        if (StrUtil.isEmpty(item.getCreatedUserId())) {
            item.setCreatedUserId(SecurityUtils.getUserId());
            item.setCreatedUserName(SecurityUtils.getUserName());
            item.setCreateTime(new Date());
        }
        item.setLastUpdatedUserId(SecurityUtils.getUserId());
        item.setLastUpdatedUserName(SecurityUtils.getUserName());
        item.setLastUpdateTime(new Date());
        item.setDeleted(0);

    }

    /**
     * 根据主键获取位置信息
     *
     * @param id 主键
     * @return StandardCodeDTO
     */
    public EamLocationInfoDTO get(String id) {
        // 查询数据
        EamLocationInfo item = this.baseMapper.selectById(id);
        EamLocationInfoDTO dto = new EamLocationInfoDTO();
        try {
            BeanUtils.copyProperties(item, dto);
        } catch (RuntimeException e) {
            throw e;
        }

        return dto;
    }

    public void setAllInfo(EamLocationInfo item) {
        QueryWrapper<EamLocationInfo> qw = new QueryWrapper<>();
        qw.lambda().eq(EamLocationInfo::getId, item.getParentId());

        EamLocationInfo EamLocationInfo = this.baseMapper.selectOne(qw);
        if (EamLocationInfo == null) {
            item.setAllId(item.getId());
            item.setAllCode(item.getLocationCode());
            item.setAllName(item.getLocationName());
        } else {
            item.setAllId(EamLocationInfo.getAllId() + "," + item.getId());
            item.setAllCode(EamLocationInfo.getAllCode() + "," + item.getLocationCode());
            item.setAllName(EamLocationInfo.getAllName() + "," + item.getLocationName());
        }
    }

    /**
     * 判断是否有下级
     *
     * @param id
     * @return
     */
    public Boolean isHaveChild(String id) {
        QueryWrapper<EamLocationInfo> qw = new QueryWrapper<>();
        qw.lambda().eq(EamLocationInfo::getParentId, id).eq(EamLocationInfo::getDeleted, 0);
        Integer count = this.baseMapper.selectCount(qw);
        return count > 0 ? true : false;
    }
}

